const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const MongoStore = require("connect-mongo")(session);
const path = require("path");
const logger = require("morgan");
const nunjucks = require("nunjucks");
const compression = require("compression");
const filters = require("./app/modules/filters.js");


const indexRoute = require("./app/routes/server.index.route");
const apiRoute = require("./app/routes/server.api.route.js");
const adminRoute = require("./app/routes/server.admin.route.js");
const locationRoute = require("./app/routes/server.location.route.js");
const h5Route = require("./app/routes/server.h5.route.js");
const fileRoute = require("./app/routes/server.file.route.js");

const app = express();


/*---------开启gzip压缩----------*/
app.use(compression({filter: (req, res)=>{
    if(req.headers["x-no-compression"]){
        return false;
    };
    return compression.filter(req, res);
}}));

/*---------打印请求日志----------*/
app.use(logger("dev"));

/*---------配置模板引擎-----------*/
const env = nunjucks.configure("./app/views", {
    autoescape: true,
    express: app,
    watch: true
});
filters && filters(env);


/*---------配置静态路径----------*/
app.use(express.static(path.join(__dirname, "static")));

/*---------解析application/json格式数据-------------*/
app.use(bodyParser.json());

/*---------解析application/x-www-form-urlencoded格式数据------------*/
app.use(bodyParser.urlencoded({extended: false}));

/*---------解析cookis--------------------*/
app.use(cookieParser());

/*---------解析session-------------*/
app.use(session({
    secret: "express_app",
    resave: true,
    saveUninitialized: true,
    cookie: {maxAge: 24 * 60 * 60 * 1000},
    store: new MongoStore({
        url: "mongodb://localhost/wanneng"
    })
}));

/*---------添加路由--------------*/
app.use("/", indexRoute);
app.use("/api", apiRoute);
app.use("/admin", adminRoute);
app.use("/location", locationRoute);
app.use("/file", fileRoute);
app.use("/h5", h5Route);

/*---------捕获404错误--------------*/
app.use((req, res, next)=>{
    let err = new Error("Error: 404, the source is not found!");
    err.status = 404;
    next(err);
});

/*---------捕获500错误--------------*/
app.use((err, req, res, next)=>{
    console.log(err);
    res.status(err.status || 500).send(err.message);
    next();
});

module.exports = app;